import os
import sys
import time
import traceback

from PySide6 import QtCore
from PySide6.QtCore import Qt
from PySide6.QtGui import QIcon, QKeySequence, QShortcut
from PySide6.QtQuick import QSGRendererInterface, QQuickWindow
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
from controllers.login.login import Login
from controllers.success import Success
from global_variables import GlobalVariables

DEBUG = True
# 设置项目目录
GlobalVariables.PROJECT_BASE_PATH = os.path.realpath(os.path.dirname(__file__)) + os.sep


class Application(QMainWindow):
    def __init__(self, app: QApplication, is_login: bool):
        super(Application, self).__init__()
        # 设置项目主对象
        self.app = app
        # 设置icon
        self.app.setWindowIcon(QIcon(GlobalVariables.PROJECT_BASE_PATH + 'resource/asset/logo/logo.ico'))


        # 判断是否登录，如果没有登录，则进入登录页面
        if not is_login:
            try:
                self.login_controller = Login(self)
                # 添加刷新快捷键
                shortcut = QShortcut(QKeySequence("Ctrl+W"), self.ui)
                shortcut.activated.connect(self.close_window)
            except Exception as e:
                traceback.print_exc()
            return

        try:
            # 登录成功后
            self.success_controller = Success(self)

            # 添加刷新快捷键
            shortcut = QShortcut(QKeySequence("Ctrl+W"), self.ui)
            shortcut.activated.connect(self.close_window)
        except Exception as e:
            traceback.print_exc()

    def close_window(self):
        result = QMessageBox.question(self, '确认退出', f'是否确认退出')
        if result != QMessageBox.StandardButton.Yes:
            return
        QApplication.quit()

    # 点击连接
    def connection_success(self, default_database: str):
        # 切换视图
        self.ui.close()
        self.w = Application(self.app, is_login=True)
        self.w.success_controller.init(default_database)
        self.w.ui.show()


def main():
    if hasattr(sys, "frozen"):
        os.environ['QTWEBENGINEPROCESS_PATH'] = os.path.abspath(os.path.dirname(sys.argv[0]))
    try:
        QtCore.QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        QQuickWindow.setGraphicsApi(QSGRendererInterface.OpenGLRhi)
        app = QApplication(sys.argv)
        app.setProperty('debug', DEBUG)
        w = Application(app, is_login=False)
        w.ui.show()
        sys.exit(app.exec())
    except SystemExit as e:
        print(time.time(), '正常退出, 退出码：%s' % e.code)
    except:
        if DEBUG:
            traceback.print_exc()
        else:
            with open(GlobalVariables.PROJECT_BASE_PATH + "error.log", 'a') as f:
                traceback.print_exc(file=f)


if __name__ == '__main__':
    main()
